package com.ssm.sport.filter;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpServletResponseWrapper;
import java.io.IOException;

/**
 * 上下文路径过滤器
 * 用于处理重定向URL，确保包含正确的上下文路径
 */
public class ContextPathFilter implements Filter {

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
            throws IOException, ServletException {
        HttpServletRequest httpRequest = (HttpServletRequest) request;
        HttpServletResponse httpResponse = (HttpServletResponse) response;
        
        String contextPath = httpRequest.getContextPath();
        
        // 如果上下文路径非空，包装响应对象以修改重定向行为
        if (contextPath != null && !contextPath.isEmpty() && !"/".equals(contextPath)) {
            chain.doFilter(request, new ContextPathResponseWrapper(httpResponse, contextPath));
        } else {
            chain.doFilter(request, response);
        }
    }

    @Override
    public void destroy() {
    }
    
    /**
     * 响应包装器，用于修改重定向URL
     */
    private static class ContextPathResponseWrapper extends HttpServletResponseWrapper {
        
        private final String contextPath;
        
        public ContextPathResponseWrapper(HttpServletResponse response, String contextPath) {
            super(response);
            this.contextPath = contextPath;
        }
        
        @Override
        public void sendRedirect(String location) throws IOException {
            // 如果重定向URL是相对路径且不以上下文路径开头，则添加上下文路径
            if (location.startsWith("/") && !location.startsWith(contextPath + "/") && !location.startsWith("/http")) {
                super.sendRedirect(contextPath + location);
                System.out.println("修改重定向URL: " + location + " -> " + contextPath + location);
            } else {
                super.sendRedirect(location);
            }
        }
    }
} 